<template>
    <div class="container-fluid p-4">
        <!-- 1. 统计卡片 -->
        <el-row :gutter="20" class="mb-4">
            <el-col :xs="24" :sm="12" :md="6" class="mb-3">
                <el-card shadow="hover" class="stats-card">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 bg-primary text-white rounded-circle p-3">
                            <i class="bi bi-journal-album"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1 text-muted">全部考核</h6>
                            <h4 class="mb-0">{{ stats.totalExams }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" class="mb-3">
                <el-card shadow="hover" class="stats-card">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 bg-success text-white rounded-circle p-3">
                            <i class="bi bi-activity"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1 text-muted">活跃考核</h6>
                            <h4 class="mb-0">{{ stats.activeExams }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" class="mb-3">
                <el-card shadow="hover" class="stats-card">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 bg-info text-white rounded-circle p-3">
                            <i class="bi bi-people-fill"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1 text-muted">参与人次</h6>
                            <h4 class="mb-0">{{ stats.totalSubmissions }}</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="6" class="mb-3">
                <el-card shadow="hover" class="stats-card">
                    <div class="d-flex align-items-center">
                        <div class="flex-shrink-0 bg-warning text-white rounded-circle p-3">
                            <i class="bi bi-graph-up-arrow"></i>
                        </div>
                        <div class="flex-grow-1 ms-3">
                            <h6 class="mb-1 text-muted">平均通过率</h6>
                            <h4 class="mb-0">{{ stats.averagePassRate }}%</h4>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 2. 筛选器 -->
        <el-card class="mb-4" shadow="never">
            <template #header>
                <div class="card-header">
                    <h5>考核管理</h5>
                </div>
            </template>
            <el-form :model="filterForm" label-width="80px" label-position="left">
                <el-row :gutter="20">
                    <el-col :sm="12" :md="6">
                        <el-form-item label="关键词">
                            <el-input v-model="filterForm.keyword" placeholder="考核标题关键词" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :sm="12" :md="6">
                        <el-form-item label="考核状态">
                            <el-select v-model="filterForm.status" placeholder="全部状态" clearable>
                                <el-option label="草稿" value="draft"></el-option>
                                <el-option label="已发布" value="published"></el-option>
                                <el-option label="进行中" value="ongoing"></el-option>
                                <el-option label="已结束" value="ended"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="12" :md="6">
                        <el-form-item label="考核类型">
                            <el-select v-model="filterForm.examSectionName" placeholder="考核类型名称" clearable>
                                <el-option label="理论考核" value="理论考核"></el-option>
                                <el-option label="实操考核" value="实操考核"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="12" :md="6">
                        <el-form-item label="课程名称">
                            <el-select v-model="filterForm.courseName" placeholder="所有课程" clearable>
                                <el-option v-for="item in courseStore.courses" :key="item.course.id"
                                    :label="item.course.title" :value="item.course.title" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :sm="12" :md="6">
                        <el-form-item label="创建人">
                            <el-input v-model="filterForm.creatorName" placeholder="创建人姓名" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :sm="12" :md="10">
                        <el-form-item label="创建时间">
                            <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" />
                        </el-form-item>
                    </el-col>
                    <el-col :sm="24" :md="8" class="text-end">
                        <el-button type="primary" @click="onSearch" :icon="Search">查询</el-button>
                        <el-button @click="onClearFilter" :icon="Refresh">重置</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>

        <!-- 3. 考核列表 -->
        <el-card shadow="never">
            <el-table :data="exams" v-loading="loading" style="width: 100%" stripe>
                <el-table-column prop="exam.title" label="考核名称" width="200" show-overflow-tooltip />
                <el-table-column prop="examSection.name" label="类型" width="120" />
                <el-table-column prop="exam.status" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.exam.status)">{{ getStatusText(row.exam.status) }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="exam.creatorId" label="创建人ID" width="100" />
                <el-table-column prop="exam.createTime" label="创建日期" width="180">
                    <template #default="{ row }">{{ formatDate(row.exam.createTime) }}</template>
                </el-table-column>
                <el-table-column prop="exam.startTime" label="开始时间" width="180">
                    <template #default="{ row }">{{ formatDate(row.exam.startTime) }}</template>
                </el-table-column>
                <el-table-column prop="exam.endTime" label="结束时间" width="180">
                    <template #default="{ row }">{{ formatDate(row.exam.endTime) }}</template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(row.exam.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 4. 分页 -->
            <el-pagination v-if="total > 0" @current-change="handlePageChange" :current-page="pagination.pageNum"
                :page-size="pagination.pageSize" :total="total" layout="total, prev, pager, next, jumper" background
                class="mt-4 justify-content-center" />
        </el-card>
    </div>
    <NewAssessmentModal v-model="modalController.popups.newAssessmentModal" :exam-data="examToEdit"
        @refresh="fetchExamList" />
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useExamStore } from '@/stores/exam.js';
import { storeToRefs } from 'pinia';
import { useCourseStore } from '@/stores/course.js';
import { Search, Refresh } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import { modalControllers } from '@/stores/modalController.js';
import NewAssessmentModal from "@/components/alert/teacher/NewAssessmentModal.vue";

const examStore = useExamStore();
const courseStore = useCourseStore();
// 注意：这里的 total 会被用于分页器的总数
const { exams, total, loading } = storeToRefs(examStore);
const modalController = modalControllers();
const examToEdit = ref(null);
// 统计数据
const stats = reactive({
    totalExams: 0,
    activeExams: 0,
    totalSubmissions: 0,
    averagePassRate: 0,
});

// 筛选表单
const filterForm = reactive({
    keyword: "",
    status: "",
    examSectionName: "",
    courseName: "",
    creatorName: "",
    dateRange: [],
});

// 分页数据
const pagination = reactive({
    pageNum: 1,
    pageSize: 10,
});

// 核心修改：分离获取统计数据的逻辑
const fetchStatistics = () => {
    // 1. 获取全部考核数量 (pageSize: -1 表示获取全部)
    // 这个调用会更新 store 中的 exams 和 total，供表格和分页器使用
    examStore.fetchExams({
        pageNum: 1,
        pageSize: 10,
    }, (allExamsData, allExamsTotal) => {
        stats.totalExams = allExamsTotal; // 直接使用后端返回的总数（或兼容处理后的长度）
    });

    // 2. 获取活跃考核数量
    examStore.fetchExams({
        status: 'ongoing', pageNum: 1,
        pageSize: 10
    }, (activeExamsData) => {
        stats.activeExams = activeExamsData.length;
    });

    // 3. 获取答卷相关统计
    examStore.fetchAllSubmissions((allSubmissions) => {
        stats.totalSubmissions = allSubmissions.length;
        const completed = allSubmissions.filter(s => s.examSubmission.gradingStatus === 'completed');
        if (completed.length > 0) {
            const passed = completed.filter(s => s.examSubmission.totalScore >= 60).length;
            stats.averagePassRate = ((passed / completed.length) * 100).toFixed(1);
        } else {
            stats.averagePassRate = 0;
        }
    });
};

// 获取用于表格展示的考核列表（分页）
const fetchExamList = () => {
    const params = {
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize,
    };

    for (const key in filterForm) {
        if (key !== 'dateRange' && filterForm[key]) {
            params[key] = filterForm[key];
        }
    }

    if (filterForm.dateRange && filterForm.dateRange.length === 2) {
        params.beginTime = filterForm.dateRange[0];
        params.endTime = filterForm.dateRange[1];
    }

    // 这个调用会更新 store 中的 exams 和 total，供表格和分页器使用
    examStore.fetchExams(params);

};

// 查询按钮
const onSearch = () => {
    pagination.pageNum = 1;
    fetchExamList();
};

// 清空筛选
const onClearFilter = () => {
    Object.keys(filterForm).forEach(key => {
        filterForm[key] = Array.isArray(filterForm[key]) ? [] : "";
    });
    onSearch();
};

// 分页改变
const handlePageChange = (newPage) => {
    pagination.pageNum = newPage;
    fetchExamList();
};

// 编辑操作
const handleEdit = async (row) => {
  try {
    // 1. 先获取考核详情
    const examDetailsResponse = await new Promise((resolve, reject) => {
      examStore.fetchExamById(row.exam.id, resolve, reject);
    });

    const examData = examDetailsResponse.exam;

    if (!examData || !examData.courseId) {
      ElMessage.error("考核数据不完整，缺少课程ID。");
      return;
    }

    // 2. 根据 courseId 获取课程详情以获得课程名称
    const courseData = await courseStore.fetchCourseDetail(examData.courseId);

    // 3. 合并数据，为模态框准备最终数据对象
    examToEdit.value = {
      ...examData,
      courseName: courseData.title
    };

    // 4. 打开弹窗
    modalController.openPopup('newAssessmentModal');

  } catch (error) {
    console.error("编辑考核时数据加载失败:", error);
    ElMessage.error("加载编辑数据失败，请稍后重试。");
  }
};

// 删除操作
const handleDelete = (examId) => {
    examStore.deleteExam(examId, () => {
        if (exams.value.length === 1 && pagination.pageNum > 1) {
            pagination.pageNum--;
        }
        fetchExamList();
    });
};

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return 'N/A';
    return dayjs(dateStr).format('YYYY-MM-DD HH:mm');
};

// 获取状态Tag类型
const getStatusTagType = (status) => {
    switch (status) {
        case 'published': return 'primary';
        case 'ongoing': return 'success';
        case 'ended': return 'info';
        case 'draft': return 'warning';
        default: return 'info';
    }
};

// 获取状态中文文本
const getStatusText = (status) => {
    const statusMap = {
        published: '已发布',
        ongoing: '进行中',
        ended: '已结束',
        draft: '草稿'
    };
    return statusMap[status] || '未知';
}

// 组件挂载时，分别获取统计数据和列表数据
onMounted(() => {
    fetchStatistics();
    fetchExamList();
    courseStore.getCourses();
});
</script>

<style scoped>
.stats-card .bi {
    font-size: 2rem;
}

.el-form-item {
    margin-bottom: 1rem;
}

.text-end {
    text-align: right;
}
</style>